// pages/orderNew/orderNew.js
import {
  getCategory,
  getProduct,
  getCart,
  postAddCart,
  postReduceCart,
  postCartDel,
  getProductDapei,
  getDapei,
  postDapeiAddCart,
  postDapeiReduceCart,
  postXuniProduct,
  getBanner
} from '../../api/index'
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: app.globalData.baseUrl,
    showCarList: false,
    moreShow: false,
    classList: [], //分类列表
    calssId: -1, //点击的分类id
    classIndexId: 0, //分类列表点击的id 第几个
    productList: [], //商品列表
    carList: [], //购物车列表
    hun:[],    //荤菜
    su:[],   //素菜
    zhuShi:[],   //主食
    daPei:[],      //搭配方式
    daPeiCar:[],     //搭配购物车   除去主食
    daPeiZhuShiCar:[],    //搭配 购物车 主食
    winHeight:0,//屏幕高度
    banners:[
      {banner:'/webImage/banner1.png'},
      {banner:'/webImage/banner1.png'},
      {banner:'/webImage/banner1.png'},
  ],
  },

  /**
   ***更多
   */

  //头部点击更多显示 
  onClickShowMore: function() {
    this.setData({
      moreShow: true
    })
  },
  //取消按钮
  onMoreCancel: function() {
    this.setData({
      moreShow: false
    })
  },

  /*
   ***个人中心
   */
  onClickUserWe: function() {
    wx.navigateTo({
      url: '../we/we',
    })
  },
  /*
   ***购物车
   */
  //点击购物车的下面
  onCarList: function() {
    this.setData({
      showCarList: !this.data.showCarList
    })
  },
  //点击遮罩层的时候
  onClickShade() {
    this.setData({
      showCarList: !this.data.showCarList
    })
  },
  //购物车列表
  getcarListData() {
    getCart().then(res => {
      if (res.state == 0) {
        var carData = res.data;
        // console.log(carData)
        var total = 0.00;
        for (var i = 0; i < carData.cart.length; i++) {
          var Price = carData.cart[i].num * parseFloat(carData.cart[i].price); //单个商品的总价
          total = total + Price; //购物车的总价格
        }
        res.data.total = total.toFixed(2)
        // console.error(res.data.total)
        this.setData({
          carList: res.data
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  //购物车+  加
  onCartAdd(e) {
    var proid = e.currentTarget.dataset.proid;
    var index = e.currentTarget.dataset.index
    console.log(index)
    postAddCart({
      proid: proid
    }).then(res => {
      if (res.state == 0) {
        if (e.currentTarget.dataset.type == "car") { //购物车
          var carData = this.data.carList;
          var num = carData.cart[index].num + 1; //单个商品的数量
          var count = carData.count++; //共多少件
          // console.log(carData.total)
          // console.log(carData.cart[index].price)
          carData.total = parseFloat(carData.total) + parseFloat(carData.cart[index].price);
          carData.total = carData.total.toFixed(2)
          carData.cart[index].num = num;
          carData.cart.count = count;
          for (var i = 0; i < this.data.productList.length; i++) {
            if (this.data.productList[i].id == carData.cart[index].proid) {
              this.data.productList[i].cartNum = num;
              console.log("++++++商品", this.data.productList[i].cartNum)
              break;
            }
          }
          console.error(carData.cart[index].num)
          this.setData({
            carList: carData,
            productList: this.data.productList
          })
        }
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  //购物车- 减
  onCartReduce(e) {
    var proid = e.currentTarget.dataset.proid;
    var index = e.currentTarget.dataset.index //购物车的下标
    // console.log(index)
    postReduceCart({
      proid: proid
    }).then(res => {
      if (res.state == 0) {
        if (e.currentTarget.dataset.type == "car") { //购物车
          var carData = this.data.carList;
          var num = carData.cart[index].num - 1;
          var count = carData.count--;
          carData.total = parseFloat(carData.total) - parseFloat(carData.cart[index].price); //计算总价格
          carData.total = carData.total.toFixed(2) //取小数点后两位
          carData.cart[index].num = num;
          carData.cart.count = count;
          console.error(carData.cart[index].num)
          for (var i = 0; i < this.data.productList.length; i++) {
            if (this.data.productList[i].id == carData.cart[index].proid) {
              this.data.productList[i].cartNum = num;
              console.log("++++++商品", this.data.productList[i].cartNum)
              break;
            }
          }
          if (num == 0) {
            carData.cart.splice(index, 1)
          }
          this.setData({
            carList: carData,
            productList: this.data.productList
          })
        }
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  //清空购物车
  onCarDel() {
    var proid = this.data.carList.cart[0].id;
    for (var i = 1; i < this.data.carList.cart.length; i++) { //获取购物车id
      proid = proid + "," + this.data.carList.cart[i].id
    }
    let data = {
      cartid: proid
    }
    postCartDel(data).then(res => {
      if (res.state == 0) {
        var carData = this.data.carList
        carData.cart.length = 0;
        this.getProductList(this.data.calssId)
        this.setData({
          carList: carData
        })
        wx.showToast({
          title: "清空成功",
          icon: 'success',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  /*
   ***商品列表
   */
  //添加
  onProAdd(e) {
    var tc = e.currentTarget.dataset.tc;
    var proid = e.currentTarget.dataset.id; //商品id
    var index = e.currentTarget.dataset.index; //下标
    postAddCart({
      proid: proid,
      tc: tc
    }).then(res => {
      if (res.state == 0) {
        var proData = this.data.productList;
        proData[index].cartNum = proData[index].cartNum + 1;
        console.log(proData[index].cartNum)
        this.setData({
          productList: proData
        })
        this.getcarListData()
      }
    })
  },
  //减
  onProReduce(e) {
    var proid = e.currentTarget.dataset.id; //商品id
    var index = e.currentTarget.dataset.index; //下标
    postReduceCart({
      proid: proid
    }).then(res => {
      if (res.state == 0) {
        var proData = this.data.productList;
        proData[index].cartNum = proData[index].cartNum - 1;
        console.log(proData[index].cartNum)
        this.setData({
          productList: proData
        })
        this.getcarListData()
      }
    })
  },
  // 自选商品 加入商品 加
  onZixuanAdd(e){
    var proid = e.currentTarget.dataset.id; //商品id
    var index = e.currentTarget.dataset.index; //下标
    var name=e.currentTarget.dataset.name;      //判断是 荤菜 素菜 主食
    if (name ==='hun'){
      this.daPeiCondition('hun', e.currentTarget.dataset )      //调用 方式 判断是否可以加入
     
    } else if (name ==='su'){
      this.daPeiCondition('su', e.currentTarget.dataset)

    } else if (name ==='zhuShi'){       //主食
      // console.log('daPeiZhuShiCar+++++++', this.data.daPeiZhuShiCar)
      if (this.data.daPeiZhuShiCar.length<1){
        postDapeiAddCart({ proid: proid }).then(res => {
          if (res.state == 0) {
            this.data.zhuShi[index].cartNum += 1;
            this.data.daPeiZhuShiCar.push(this.data.zhuShi[index])      //向搭配 主食的购物车 追加
            this.setData({
              zhuShi: this.data.zhuShi
            })
          }
        })   
      }else{
        wx.showToast({
          title: '主食最多选择1个',
          icon: 'none',
          duration: 2000
        })
      }
    }
  },
  //自选菜单 套餐 是否可以选择
  daPeiCondition(name,data) {     //name 数组名，     data 传过来的值
    console.log(this.data[name])
    console.log("this.data.daPeiCar++++1111++++", this.data.daPeiCar)
    console.log('this.data[name][data.index].cartNum+++++', this.data[name][data.index].cartNum)
    if(this.data[name][data.index].cartNum<1){        //判断同商品只能购买一次
      console.log(this.data.daPeiCar.length)
      let hunCaiCount = 0
      let suCaiCount = 0  
      console.log('长度+++', this.data.daPeiCar.length)
      if(this.data.daPeiCar.length<3){        //判断是否 菜品 选够了三个
        
        console.log("this.data.daPeiCar 之前的数据", this.data.daPeiCar)
        var addDaPeiCar = this.data.daPeiCar      //判断是否可以在加一
        console.log("addDaPeiCar+++++++++", addDaPeiCar)
        addDaPeiCar.push(this.data[name][data.index])
        console.log("this.data.daPeiCar++++1111++++", this.data.daPeiCar)
        addDaPeiCar.forEach(function(item,index,arr){      //判断在次 加入的菜是否可以 加入
          // console.log(item)
          if (item.hunsu==1){
            hunCaiCount++
          } else if (item.hunsu==2){
            suCaiCount++
          }
        },this)  
        console.log('hunCaiCount++++荤菜数量', hunCaiCount)
        console.log('suCaiCount++++素菜数量', suCaiCount)
        var dapeiCaiSome=this.data.daPei.some(function(item,index,arr){
          console.log("hunCaiCount <= item.hun++++",hunCaiCount <= item.hun)
          return hunCaiCount <= item.hun && suCaiCount <= item.su
        },this)
        if (dapeiCaiSome){      //是否可以选择 
          postDapeiAddCart({ proid: this.data[name][data.index].id }).then(res => {
            console.error("++11111111+++++", this.data.daPeiCar)
            if (res.state == 0) {
              // this.data.daPeiCar.push(this.data[name][data.index])
              this.data[name][data.index].cartNum+=1        //加一
              this.setData({
                [name]:this.data[name]
              })
            }
          })  
        }else{
          addDaPeiCar.splice(addDaPeiCar.length-1,1)
          wx.showToast({
            title: '不满足套餐规则',
            icon:'none',
            duration:2000
          })
        }
        console.log("dapeiCaiSome+++++++", dapeiCaiSome)
      }else{
        wx.showToast({
          title: '菜品只能选择三个',
          icon:'none',
          duration:2000
        })
      }
    }else{
      wx.showToast({
        title: '同商品一次只能购买一个',
        icon:'none',
        duration:2000
      })
    }
  },
  ///自选商品 减商品
  onZixuanReduce(e){
    var proid = e.currentTarget.dataset.id; //商品id
    var index = e.currentTarget.dataset.index; //下标
    var name = e.currentTarget.dataset.name;      //判断是 荤菜 素菜 主食
    if (name === 'hun') {
      this.ziZuanJian(name,e.currentTarget.dataset)     // 荤菜和 素菜 同算法 -1
    } else if (name === 'su') {
      this.ziZuanJian(name, e.currentTarget.dataset)     // 荤菜和 素菜 同算法 -1
    } else if (name === 'zhuShi') {
      console.log("zhuShi", this.data.daPeiZhuShiCar, 'index+++', e.currentTarget.dataset.index)
        postDapeiReduceCart({ proid: proid }).then(res => {
          if (res.state == 0) {
            this.data.zhuShi[index].cartNum -= 1;
            this.data.daPeiZhuShiCar=[]    //删除主食下面的哪个
            console.log(this.data.daPeiZhuShiCar)
            this.setData({
              zhuShi: this.data.zhuShi
            })
          }
        })
    }
  },
 //自选商品 减商品 计算
 ziZuanJian(name,data){
   if (name !='zhuShi'){
     postDapeiReduceCart({ proid: this.data[name][data.index].id }).then(res => {
       if (res.state == 0) {
         this.data[name][data.index].cartNum -= 1;      //减一
         var jianIndex = this.data.daPeiCar.findIndex((item,index,arr)=>{
           console.log("findIndex  item+++++",item)
           return item.id === this.data[name][data.index].id
         })
         console.log('jianIndex', jianIndex)
         this.data.daPeiCar.splice(jianIndex,1)
         console.log(this.data.daPeiCar,'++++++this.data.daPeiCar')
         this.setData({
           [name]: this.data[name]
         })
       }
     })
     
   }
   
 },
 // 生成套餐
  onClickCreatTaoCan(){
    if(this.data.daPeiCar.length==3){   //满足菜 三个菜
      if(this.data.daPeiZhuShiCar.length==1){     //是否选择了主食
        var hunCaiCount=0;    //荤菜 数
        var suCaiCount=0;    //素菜数
        var strName=[]
        this.data.daPeiCar.forEach(function(item,index,arr){
          strName.push(item.name)
          if (item.hunsu===1){
            hunCaiCount++;      //荤菜 +1
          }else if(item.hunsu==2){
            suCaiCount++;     //素菜
          }
        })
        strName.push(this.data.daPeiZhuShiCar[0].name)      // 生成套餐的名字 加了主食的
        var daPeifilter=this.data.daPei.filter(function(item,index,arr){
            return hunCaiCount === item.hun && suCaiCount === item.su
        })
        console.log('strName++++', strName)
        console.log(daPeifilter)
        var data={
          name: strName.join('+'),      //名字
          price: daPeifilter[0].price,    //价格
          thumb: daPeifilter[0].imgurl
        }
        postXuniProduct(data).then(res => {
          if (res.state == 0) {     //生成套餐 接口
            this.getProductList(-1);      //重新加载列表
            this.getcarListData()
          }
        })
      }else{
        wx.showToast({
          title: '请选择一份主食',
          icon: 'none',
          duration: 2000
        })
      }
    }else{
      wx.showToast({
        title: '请选择三个菜',
        icon:'none',
        duration:2000
      })
    }
   
  },
  //跳到详情页
  onJumpDetails(e) {
    //  console.log(e.currentTarget.dataset.id)
    wx.navigateTo({
      url: '../details/details?id=' + e.currentTarget.dataset.id,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //加载baner
    getBanner().then(res=>{
      if(res.state==0){
        this.setData({
          banners:res.data
        })
      }
    })
    //加载 搭配方式
    getDapei().then(res => {
      if (res.state == 0) {
        this.data.daPei = res.data
      }
    })

    //加载下面的商品列表
    // console.log(this.data.classList)
    // console.log(this.data.classList[0].id)

  },

  //点击分类的时候 跳商品
  onClassClick(e) {
    console.log(e.currentTarget.dataset)
    this.data.calssId = e.currentTarget.dataset.id

    this.getProductList(this.data.calssId);
    this.setData({
      calssId: e.currentTarget.dataset.id,
      classIndexId: e.currentTarget.dataset.index
    })
  },
  //加载下面的商品列表
  getProductList(id) {
    if (id != -1) {
      getProduct(id).then(res => {
        if (res.state == 0) {
          this.setData({
            productList: res.data
          })
          console.log(res.data)
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      })
    }else{
      getProductDapei().then(res=>{     //自选菜单
        if(res.state==0){
          var hunCai=[]       //荤菜
          var suCai=[]      //素菜
          var zhuShi=[]     //主食
          this.data.daPeiCar=[]       //自选菜单 菜品个数
          this.data.daPeiZhuShiCar=[]     //自选菜单  主食个数
          res.data.forEach(function(item,index,arr){
            //生成菜单
            if (item.hunsu==1){  //荤菜
                hunCai.push(item)
            } else if (item.hunsu==2){      //素菜
              suCai.push(item)
            } else if (item.hunsu == 3) {     //主食
              if (item.cartNum>0){
                this.data.daPeiZhuShiCar.push(item)
                console.log(this.data.daPeiZhuShiCar)
              }
              zhuShi.push(item)
            }
            if (item.cartNum > 0 && item.hunsu!=3) {     //购物车的数  不包括主食
              this.data.daPeiCar.push(item)
            }
          },this)
          console.log("商品初次加载搭配的购物车 this.data.daPeiCar",this.data.daPeiCar)
          this.setData({
            hun: hunCai,
            su: suCai,
            zhuShi: zhuShi
          })
        }else{
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      })
    }
    // console.log(id) 

  },
  //点击选好了 
  onSumbitOk() {
    wx.navigateTo({
      url: '../okOrder/okOrder',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this
    wx.getSystemInfo({
      success: function (res) {
        console.log(res.windowHeight)
        let windowHeight = res.windowHeight;
        let windowWidth = res.windowWidth;
        console.log(windowWidth)
        let rate = 750 / windowWidth;
        console.log(rate)
        let marginTop = windowHeight * rate  // 将屏幕高度转成了 rpx 值
        console.log(marginTop)
        that.setData({
          winHeight: marginTop
        });
      }
    });
    //加载分类    
    getCategory().then(res => {
      if (res.state == 0) {
        console.log(res.data)
        that.data.classList = res.data
        let data = {
          id: 0,
          name: "推荐"
        }
        that.data.classList.unshift(data); //向数组第一个插值
        let taoCan = {
          id: -1,
          name: "自选菜单"
        }
        that.data.classList.unshift(taoCan); //向数组第一个插值   套餐单品
        // that.data.calssId=that.data.classList[0].id
        that.getProductList(that.data.calssId) //调商品列表
        that.setData({
          classList: res.data
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
    that.getcarListData() //加载购物车
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})